package sampleapp.web.pages;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;

import sampleapp.logic.UserLogic;

import com.google.inject.Inject;

public class RegistrationPanel extends Panel {
	private static final long serialVersionUID = 1L;

	@Inject
	private UserLogic loginLogic;
	
	public RegistrationPanel(String id) {
		super(id);
		add(new FeedbackPanel("feedback"));
		add(new RegistrationForm("registrationForm"));
	}

	private class RegistrationForm extends StatelessForm<Void> {
		private static final long serialVersionUID = 1L;
		private final ValueMap properties = new ValueMap();
		private TextField<String> email;
		private PasswordTextField password;
		private PasswordTextField confirmPassword;

		public RegistrationForm(String id) {
			super(id);
			add(email = new TextField<String>("email",
					new PropertyModel<String>(properties, "email")));
			add(password = new PasswordTextField("password",
					new PropertyModel<String>(properties, "password")));
			add(confirmPassword = new PasswordTextField("confirmPassword",
					new PropertyModel<String>(properties, "confirmPassword")));

			email.setType(String.class);
			password.setType(String.class);
			confirmPassword.setType(String.class);
		}
		
		@Override
		protected void onSubmit() {
			if (password.getValue().equals(confirmPassword.getValue())) {				
				if (loginLogic.registerUser(email.getValue(), password.getValue())) {
					RequestCycle.get().setRedirect(true);
					RequestCycle.get().setResponsePage(LoginPage.class);
				} else {
					error("User already exists");
				}
			}
		}

	}

}
